// Copyright (C) 2023 即时通讯网(52im.net) & Jack Jiang.
// The RainbowChat Project. All rights reserved.
// 
// 【本产品为著作权产品，合法授权后请放心使用，禁止外传！】
// 【本次授权给：<北京小羊驼科技有限公司>，授权编号：<NT231212144350>，代码指纹：<A.702363430.550>，技术对接人微信：<ID: wxid_wbyootvkdcgj22>】
// 【授权寄送：<收件：苏先生、地址：北京市大兴区北京密码西区6号楼1单元301、电话：18613885610、邮箱：bd@huiyuanxiang-inc.com>】
// 
// 【本系列产品在国家版权局的著作权登记信息如下】：
// 1）国家版权局登记名(简称)和权证号：RainbowChat    （证书号：软著登字第1220494号、登记号：2016SR041877）
// 2）国家版权局登记名(简称)和权证号：RainbowChat-Web（证书号：软著登字第3743440号、登记号：2019SR0322683）
// 3）国家版权局登记名(简称)和权证号：RainbowAV      （证书号：软著登字第2262004号、登记号：2017SR676720）
// 4）国家版权局登记名(简称)和权证号：MobileIMSDK-Web（证书号：软著登字第2262073号、登记号：2017SR676789）
// 5）国家版权局登记名(简称)和权证号：MobileIMSDK    （证书号：软著登字第1220581号、登记号：2016SR041964）
// * 著作权所有人：江顺/苏州网际时代信息科技有限公司
// 
// 【违法或违规使用投诉和举报方式】：
// 联系邮件：jack.jiang@52im.net
// 联系微信：hellojackjiang
// 联系QQ号：413980957
// 授权说明：http://www.52im.net/thread-1115-1-1.html
// 官方社区：http://www.52im.net
package com.x52im.rbchat.logic.chat_root.face;

import android.app.Activity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.FrameLayout;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;

import androidx.viewpager.widget.PagerAdapter;
import androidx.viewpager.widget.ViewPager;

import com.eva.android.widget.AFragment;
import com.eva.android.widget.WidgetUtils;
import com.x52im.rbchat.MyApplication;
import com.x52im.rbchat.logic.chat_root.model.FaceEntity;

import com.x52im.rbchat.R;

import java.util.List;

/**
 * Emoji表情页面各个表情的显示页面
 *
 * @author FreeMan
 * @since 7.2
 */
public class EmojiPageFragment extends AFragment {

    public static final int EMOJI_COLUMNS = 7;//列数
    public static final int EMOJI_ROWS = 4;//行数
    // 每一页的表情个数，不含删除键
    public static final int ITEM_PAGE_COUNT = EMOJI_COLUMNS * EMOJI_ROWS - 1;//最后一个是删除键

    private ViewPager mPagerFace;
    private LinearLayout pagePointLayout;
    private Activity aty;
    private GridView[] allPageViews;
    private RadioButton[] pointViews;
    private FaceBoardView.FaceOnOperationListener listener;
    private static List<FaceEntity> datas;

    @Override
    protected View inflaterView(LayoutInflater layoutInflater, ViewGroup viewGroup, Bundle bundle) {
        aty = getActivity();
        View rootView = layoutInflater.inflate(R.layout.chatting_face_emojipage_fragment, null);
        return rootView;
    }

    @Override
    protected void initData() {
        super.initData();
        datas = MyApplication.getInstance2().getIMClientManager().getFaceDataProvider().getFaceDatas();
        addEmptyDatas(); //添加空白按钮到datas中
    }

    @Override
    protected void initWidget(View rootView) {
        super.initWidget(rootView);
        mPagerFace = (ViewPager) rootView.findViewById(R.id.frag_pager_face);
        pagePointLayout = (LinearLayout) rootView.findViewById(R.id.frag_point);

        // 适配手机屏幕分辨率-------------------------------------------------------------START-------
        DisplayMetrics dm = rootView.getContext().getResources().getDisplayMetrics();
        int screenHeight = dm.heightPixels;
        int screeWidth = dm.widthPixels;
        // 设置最大边长为120像素，横向上如有多余空间，系统会以单元格间距均匀填充
        int gridSize = Math.min(120,  screeWidth / EMOJI_COLUMNS);
        int paddingTop = 15;
        int pagerHeight = gridSize * EMOJI_ROWS + paddingTop; // 表情页面容器(不含底部的页面切换小圆点控件)高度
        System.out.println("表情页面尺寸(像素), 手机屏幕=" + screenHeight + "*" + screeWidth
                + ", 表情页面高度=" + pagerHeight);
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, pagerHeight);
        mPagerFace.setLayoutParams(params);
        mPagerFace.setPadding(0, paddingTop, 0, 0);
        // 适配手机屏幕分辨率--------------------------------------------------------------END--------

        int total = datas.size(); //一个表情包的表情总数
        int pages = total / ITEM_PAGE_COUNT + (total % ITEM_PAGE_COUNT == 0 ? 0 : 1); //一个表情包的总页面数
//        pages = (int) Math.ceil(getDisplayCount() / (float) ITEM_PAGE_COUNT); // ceil: 大于或等于参数值的最小整数，与上面通过余数判断的效果相同

        allPageViews = new GridView[pages]; //一个表情包的所有页面
        pointViews = new RadioButton[pages]; //一个表情包的所有滑动小圆点

        for (int x = 0; x < pages; x++) {
            int start = x * ITEM_PAGE_COUNT; //每个页面中第一个表情在所有表情中的索引
            int end = (start + ITEM_PAGE_COUNT) > total ? total
                    : (start + ITEM_PAGE_COUNT); // 每个页面中最后一个表情的索引+1
            final List<FaceEntity>itemDatas = datas.subList(start,end); //每个页面中的表情集合
            GridView view = new GridView(aty); //一个表情包中的一个页面
            view.setTag(x); // 标记第几页 by Freeman ---【2】处用到----
            EmojiGridAdapter iEmojiAdapter = new EmojiGridAdapter(view.getContext(), itemDatas, start);

            view.setNumColumns(EMOJI_COLUMNS);
            view.setHorizontalSpacing(1);
            view.setVerticalSpacing(1);
            view.setStretchMode(GridView.STRETCH_COLUMN_WIDTH);
            view.setCacheColorHint(0);
            view.setPadding(2, 0, 2, 0);
            view.setBackgroundResource(android.R.color.transparent);
            view.setSelector(android.R.color.transparent);
            view.setVerticalScrollBarEnabled(false);
            view.setGravity(Gravity.CENTER);
            view.setLayoutParams(new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT,
                    FrameLayout.LayoutParams.WRAP_CONTENT));
            view.setAdapter(iEmojiAdapter);

            view.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view,int position, long id) {

                    //  // parent.getTag()获取第几页 by Freeman ---【1】处设置----
                    int index = position + (Integer) parent.getTag() * ITEM_PAGE_COUNT; // position是每个页面中独立的索引， 前面的页面数*每页表情个数+本页面中独立的索引，就得出在整个数据中的索引
                    int count = getDisplayCount();
                    if (position == ITEM_PAGE_COUNT || index >= count) { // 如果页面中独立的序号刚好每页表情个数(不含删除按钮)，说明是最后一个，那这个位置就应该是删除按钮
                        if (listener != null) {
                            listener.selectedBackSpaceInIEmoji();
                        }
                    } else {
                        FaceEntity iEmoji = itemDatas.get(position);
                        String text = iEmoji.getDesc();
                        if (!TextUtils.isEmpty(text)) { // 有可能是空白表情按钮，其数据元素值设置的空字符串(详见addEmptyDatas())，所以需要判断，对于空白表情忽略
                            if (listener != null) {
                                listener.selectedIEmoji(iEmoji);
                            }
                        }
                    }

                }
            });
            allPageViews[x] = view;

            RadioButton tipPoint = new RadioButton(aty);
            tipPoint.setBackgroundResource(R.drawable.selector_chat_face_pager_indicator);
            RadioGroup.LayoutParams layoutParams = new RadioGroup.LayoutParams(
                    WidgetUtils.dip2px(aty,5), WidgetUtils.dip2px(aty,5));

            if (x != 0) {layoutParams.leftMargin = WidgetUtils.dip2px(aty, 6);}
            pagePointLayout.addView(tipPoint, layoutParams);
            if (x == 0) {tipPoint.setChecked(true); }

            pointViews[x] = tipPoint;
        }

        PagerAdapter facePagerAdapter = new FacePagerAdapter(allPageViews);
        mPagerFace.setAdapter(facePagerAdapter);
        mPagerFace.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {

            @Override
            public void onPageSelected(int index) {
                pointViews[index].setChecked(true);
            }

            @Override
            public void onPageScrolled(int arg0, float arg1, int arg2) {
            }

            @Override
            public void onPageScrollStateChanged(int arg0) {
            }
        });
    }

    public static class FacePagerAdapter extends PagerAdapter {
        private final GridView[] gridViewList;

        public FacePagerAdapter(GridView[] gridViewList) {
            this.gridViewList = gridViewList;
        }

        @Override
        public int getCount() {
            return gridViewList.length;
        }

        @Override
        public boolean isViewFromObject(View arg0, Object arg1) {
            return arg0 == arg1;
        }

        @Override
        public int getItemPosition(Object object) {
            return super.getItemPosition(object);
        }

        @Override
        public void destroyItem(View arg0, int arg1, Object arg2) {
            ((ViewPager) arg0).removeView(gridViewList[arg1]);
        }

        @Override
        public Object instantiateItem(View arg0, int arg1) {
            ((ViewPager) arg0).addView(gridViewList[arg1]);
            return gridViewList[arg1];
        }
    }

    public void setOnOperationListener(FaceBoardView.FaceOnOperationListener iOnOperationListener) {
        this.listener = iOnOperationListener;
    }

    // 包含空表情，不包含删除按钮
    public static int getDisplayCount() {
        return datas.size();
    }

    private static void addEmptyDatas() {
        //补充最后一页少的表情
        int tmp = datas.size() % ITEM_PAGE_COUNT;
        if (tmp != 0) {
            int tmp2 = ITEM_PAGE_COUNT - (datas.size() - (datas.size() / ITEM_PAGE_COUNT) * ITEM_PAGE_COUNT);
            for (int i = 0; i < tmp2; i++) {
                datas.add(new FaceEntity("", "", null));
            }
        }
    }

}
